<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class AdminGoodsController extends Controller
{
    //
    public function getIndex()
    {
    	$res = DB::table('goods_create')
    		->join('goods_brand','goods_create.brand','=','goods_brand.id')
    		->select('goods_create.*','goods_brand.brand')
    		->get();
        $state = [0=>'新添加',1=>'在售',2=>'限时特卖',3=>'下架'];
     //    foreach ($res as $key => $value) {
     //        $res[$key]['size'] = explode(',',$res[$key]['size']);
     //    }
        
    	// echo "<pre>";
    	// var_dump($res);
    	// exit;
    	return view('admin/goods/goods_index',['res'=>$res,'state'=>$state]);
    }

    public function getCreate()
    {
    	$brand = DB::table('goods_brand')->get();
    	$type = DB::table('goods_type')->orderBy('pid')->get();
    	return view('admin/goods/goods_create',['brand'=>$brand,'type'=>$type]);
    }

    public function postCreate(Request $request)
    {
    	$data = $request->except('_token','picname');
        
    	$file = $request->hasFile('picname');
    	if($file) {
            //获取图片后缀
            $profix = $request->file('picname')->getClientOriginalExtension();
            //随机图片名
            $name = rand(10000,99999).time();
            $request->file('picname')->move('./goods/',$name.'.'.$profix);
        }
        $data['picname'] = '/goods/'.$name.'.'.$profix;
        $data['addtime'] = time();
        $data['size'] = implode(',',$data['size']);
    	$res = DB::table('goods_create')->insert($data);
    	if($res) {
    		return redirect('/admin/goods/index');
    	} else {
    		return back();
    	}
    }

    public function getEdit(Request $request)
    {
        $id = $_GET['id'];
        $res = DB::table('goods_create')->where('id',$id)->first();
        $brand = DB::table('goods_brand')->lists('id','brand');
        $type = DB::table('goods_type')->lists('id','name');
                // ->join('goods_type','goods_create.typeid','=','goods_type.id')
                // ->join('goods_brand','goods_brand.id','=','goods_create.brand')
                // ->select('goods_create.*','goods_brand.brand','goods_type.name')
                // ->where('goods_create.id',$id)
                // ->get();
        // var_dump($type);
        // var_dump($brand);
        // var_dump($res);
        return view('admin/goods/goods_edit',['res'=>$res,'brand'=>$brand,'type'=>$type]);
    }

    public function postUpdate(Request $request)
    {
        $id = $request->input('id');
        $data= $request->except('_token','id');
        $res = DB::table('goods_create')->where('id',$id)->update($data);
        if($res) {
            return redirect('/admin/goods');
        } else {
            return back();
        }
    }
}
